import { getList } from '@/common/api/common/list.js';
import { ref, reactive, toRefs } from 'vue';
export default function() {
	const data = reactive({
		host: 'api',
		// 获取list的key
		key: '',
		// 数据列表
		dataList: [],
		//当前页面
		page: 1,
		// 每页数据条数
		pageSize: 10,
		// 请求地址
		url: '',
		// 请求方式
		method: 'GET',
		// 查询数据的参数
		params: {},
		// 是否加载中
		loading: false,
		// 是否显示加载状态-骨架屏
		showSkeleton: true,
		// 是否显示加载中
		showLoading: true,
		// 是否是触底加载
		onReachBottomLoad: false,
		// 是否结束
		end: false,
		// 加载更多数据
		loadMore: {
			show: false,
			status: 'more',
			txt: {
				contentdown: '上拉加载更多',
				contentrefresh: '正在加载',
				contentnomore: '没有更多数据啦~'
			}
		}
	});
	// 获取数据
	const getDataList = async (o = {}) => {
		for (let key in o) {
			data[key] = o[key];
		}
		if (data.showLoading) {
			data.loading = true;
			uni.showLoading({
				title: '加载中'
			})
		}
		if (!data.onReachBottomLoad) data.page = 1;
		// data.showSkeleton = true;
		try {
			const res = await getList({
				url: data.url,
				data: {
					page: data.page,
					pagesize: data.pageSize,
					...data.params
				},
				method: data.method,
				host: data.host
			});
			let list = res.data;
			if (data.key) {
				const keys = data.key.split('.');
				keys.forEach(item => {
					list = list[item];
				})
			}
			const count = +res.data.count || +res.data.total || res.data.takeorders_infos && ((+res.data.takeorders_infos.winner_num) + (+res.data.takeorders_infos.nowin_num)) || null;
			if (data.page == 1) {
				data.dataList = list;
			} else {
				data.dataList.push.apply(data.dataList, list);
			}
			data.loadMore.status = ((count && data.dataList.length >= count) || list.length == 0) ? 'noMore' : 'more';
			if (!count && list.length >= data.pageSize) data.loadMore.status = 'more';
			if (!count && list.length < data.pageSize) data.loadMore.status = 'noMore';
			data.loadMore.show = data.dataList.length > 0;
			// console.log('data.dataList', data.dataList)
			setTimeout(() => {
				data.showSkeleton = false;
				data.loading = false;
				data.onReachBottomLoad = false;
				uni.hideLoading();
			}, 100)
			return Promise.resolve(res.data);
		} catch (error) {
			console.warn('请求列表出错：', error);
			data.loading = false;
			data.showSkeleton = false;
			data.onReachBottomLoad = false;
			return Promise.reject(error);
		}
	}
	// 触底
	const reachBottom = () => {
		if (data.loadMore.status == 'noMore' || data.loadMore.status == 'noData') return false;
		data.loadMore.show = true;
		data.loadMore.status = 'loading';
		data.page++;
		data.onReachBottomLoad = true;
		data.showLoading = false;
		getDataList();
	}
	// 下拉刷新
	const pullDownRefresh = async () => {
		data.page = 1;
		data.showLoading = true;
		await getDataList();
		uni.showToast({
			icon: 'success',
			title: '刷新成功'
		})
		uni.stopPullDownRefresh();
	}
	return {
		getDataList,
		reachBottom,
		pullDownRefresh,
		...toRefs(data)
	}
}
